<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 消息提示 -->
      <el-alert
        show-icon=""
        title="注意：只允许为第三级分类设置相关参数！"
        :closable="false"
        type="warning"
      >
      </el-alert>

      <!-- 级联选择器 -->
      <el-row class="cate">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="cateListKeys"
            :options="catelist"
            expand-trigger="hover"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab栏区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >

          <!-- 表格区域 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引号 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 表格区域 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引号 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 表单区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改的对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 表单区域 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //商品分类数据
      catelist: [],
      //表单选中项表单值
      cateListKeys: [],
      //级联选择器配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },

      //默认激活的数据
      activeName: 'many',

      //控制添加对话框的显示与隐藏
      addDialogVisible: false,

      //添加对话框表单数据
      addForm: {
        attr_name: '',
      },

      //添加对话框表单的验证对象
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },

      //动态参数的表格数据
      manyTableData: [],

      //静态属性的表格属性
      onlyTableData: [],

      //控制修改对话框的显示与隐藏
      editDialogVisible: false,
      //修改的对话框的表单数据
      editForm: {
        attr_name: '',
      },

      //修改表单的验证对象
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //获取商品分类数据列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败！')
      }
      this.catelist = res.data
    },
    //级联选择器表单内发生变化触发的事件
    handleChange() {
      this.getParamsData()
    },
    //当tab切换时触发的事件
    handleTabClick() {
      //当tab栏切换，也得重新发起请求，获取对应tab栏的数据列表
      this.getParamsData()
    },

    //获取参数列表
    async getParamsData() {
      //如果级联选择器绑定的数组的长度不等于3，则把数组清空
      if (this.cateListKeys.length !== 3) {
        this.cateListKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      //绑定的数组长度等于3,然后发起请求，获取参数列表,首先得先获取第三层级的id
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )
      if (res.meta.status !== 200) {
        return this.$$message.error('获取参数列表失败！')
      }

      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        //给每一个item都加两个属性 inputVisible，inputValue
        //控制按钮与文本框的切换
        item.inputVisible = false
        //给每一个文本框双向绑定一个数据
        item.inputValue = ''
      })
      console.log(res.data)

      //进行判断，如果获取的是动态参数的数据列表，就给特定的数据赋值
      if (this.activeName == 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },

    //触发添加对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },

    //点击添加按钮触发的添加事件
    addParams() {
      //首先先预校验
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        //否则校验成功,然后发起请求
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败！')
        }
        this.addDialogVisible = false
        this.$message.success('添加参数成功！')
        this.getParamsData()
      })
    },

    //关闭修改对话框触发的事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },

    //点击修改按钮展示修改对话框
    async showEditDialog(id) {
      //根据id查询参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        {
          attr_sel: this.activeName,
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败！')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },

    //点击确定修改该参数
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        //发起网络请求
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败！')
        }
        this.$message.success('修改参数成功！')
        this.editDialogVisible = false
        this.getParamsData()
      })
    },

    //点击删除按钮触发的事件
    async deleteParams(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((error) => error)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除该参数')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败！')
      }
      this.$message.success('删除成功！')
      this.getParamsData()
    },

    //当摁下了回车键和表单失去焦点都会触发该事件
    handleInputConfirm(row) {
      //该事件会让inputVisible = fasle，

      //如果输入的值不合法，
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      //如果输入的值合法，则执行以下操作
      //把表单的值添加到那个数组中，然后换为按钮，并且把表单的值设为空，然后在发起请求，添加到数据库
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      row.inputVisible = false
      this.setValues(row)
    },
    //点击按钮触发的事件
    showInput(row) {
      //点击按钮，显示文本框
      row.inputVisible = true
      //让文本框自动获得焦点
      //$nextTick 方法的作用 ，就是当页面上元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    //修改参数触发的事件
    async setValues(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败！')
      }
      this.$message.success('修改参数成功！')
    },
    //点击关闭标签触发的事件
    handleClose(index, row) {
      //把那个要删除的索引传过来，从数组中删除对于标签
      row.attr_vals.splice(index, 1)
      //发送网络请求
      this.setValues(row)
    },
  },

  //计算属性
  computed: {
    //按钮是否禁用
    isBtnDisabled() {
      //如果级联选择器双向绑定的数组的长度不为3，则为true，否则为false
      if (this.cateListKeys.length !== 3) {
        return true
      }
      return false
    },

    //获取第三层级的id
    cateId() {
      if (this.cateListKeys.length !== 3) {
        return null
      }
      return this.cateListKeys[2]
    },

    //对话框的标题的计算
    titleText() {
      if (this.activeName == 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
  },
}
</script>

<style lang="less" scoped>
.cate {
  margin: 15px 0;
}

.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>